package org.bear.bundle.framework.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.bear.bundle.framework.controller.MessageType.Type;

public class AgentController extends MessageController {

	private static Properties properties = new Properties();

	private AgentPluginStatusTask agentPluginStatusTask = new AgentPluginStatusTask();

	public AgentController(String osgiName) {
		final String osgiPluginNameString = osgiName;
		this.setOsgiName(osgiName);

		initProperties();

		startSendStatus(osgiPluginNameString);
	}

	/**
	 * 送回客户端插件状态
	 * 
	 * @param osgiName
	 */
	void startSendStatus(final String osgiName) {
		Map<String, Object> pluginMap = new HashMap<String, Object>();
		pluginMap.put("pluginName", osgiName);
		pluginMap.put("ip", getIP());
		pluginMap.put("proxyIp", proxyIp);

		agentPluginStatusTask.sendPluginStatus(pattern, brokerUrl, username,
				password, pluginMap);
	}

	/**
	 * 停止送回插件状态
	 */
	public void stopSendStatus() {
		agentPluginStatusTask.stop();
	}

	@Override
	public void initProperties() {
		InputStream inputStream = null;
		try {
			inputStream = new FileInputStream(new File("mqAgent.properties"));
			properties.load(inputStream);

			brokerUrl = properties.getProperty("client.mq.url").trim();
			username = properties.getProperty("client.mq.username").trim();
			password = properties.getProperty("client.mq.password").trim();
			ip = properties.getProperty("client.ip").trim();
			pattern = properties.getProperty("client.status.pattern").trim();

			if (properties.getProperty("client.proxyip") == null) {
				proxyIp = "";
			} else {
				proxyIp = properties.getProperty("client.proxyip").trim();
			}

		} catch (Exception e) {
			this.outinfo("AGENT_INIT_PROPERTIES", "客户端初始化参数异常", Type.EXCEPTION,
					e.toString());
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				this.outinfo("AGENT_INIT_PROPERTIES", "客户端关闭IStream异常",
						Type.EXCEPTION, e.toString());
			}
		}

	}

	public String getIP() {
		return ip;
	}

	private String proxyIp;

}
